﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Hosting;
using Microsoft.Practices.Unity;

namespace JXT.PrimaryKey.Batman.Core.Container.Unity
{
    /// <summary>
    /// 每Http请求对象管理器
    /// </summary>
    public class PerHttpContextLifetimeManager : LifetimeManager
    {
        private HttpContextBase _context;
        private Func<object, object> _factory;
        private readonly Guid _key = Guid.NewGuid();

        public PerHttpContextLifetimeManager()
        {
            _context = new HttpContextWrapper(HttpContext.Current);
            _factory = t => t;
        }

        public PerHttpContextLifetimeManager(Func<object, object> factory)
            : this()
        {
            _factory = factory;
        }

        public override object GetValue()
        {
            return _context.Items[_key];
        }

        public override void RemoveValue()
        {
            object obj = _context.Items[_key];
            if (obj is IDisposable)
            {
                (obj as IDisposable).Dispose();
                obj = null;
            }
            _context.Items.Remove(_key);
        }

        public override void SetValue(object newValue)
        {
            _context.Items[_key] = _factory(newValue);
        }
    }
}
